package com.study.talk.app.login.fragment;

import static android.content.Context.MODE_PRIVATE;
import static androidx.navigation.fragment.FragmentKt.findNavController;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.study.talk.R;
import com.study.talk.app.base.BaseActivity;
import com.study.talk.app.base.BaseFragment;
import com.study.talk.app.home.HomeActivity;
import com.study.talk.app.login.LoginActivity;
import com.study.talk.netty.message.response.LoginResponse;
import com.study.talk.util.AppExecutor;
import com.study.talk.util.GsonInstance;
import com.study.talk.util.ToastUtil;
import com.study.talk.util.alert.AlertUtil;

public class LoadingFragment extends BaseFragment {

    private LoginActivity activity;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.activity = (LoginActivity) getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_loading, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        assert getArguments() != null;
        LoginResponse loginResponse = GsonInstance.instance.fromJson(getArguments().getString("loginResponse", ""), LoginResponse.class);
        if (loginResponse.getUserInfo().getAvatar() == null || loginResponse.getUserInfo().getAvatar().isEmpty()) {
            AppExecutor.getInstance().MAIN_HANDLER().post(() -> {
                AlertUtil.show(activity, "提醒", "个人信息待完善", b -> {
                    findNavController(this).navigate(R.id.action_loadingFragment_to_setUserInfoFragment, getArguments());
                });
            });
        } else {
            ToastUtil.showToast(requireContext(), "登录成功");
            handleLoginResponse(loginResponse);
            SharedPreferences preferences = activity.getSharedPreferences("account", MODE_PRIVATE);
            preferences.edit().putString("username", loginResponse.getUsername()).putString("password", loginResponse.getUser().getPassword()).apply();
            AppExecutor.getInstance().MAIN_HANDLER().postDelayed(() -> {
                startActivity(new Intent(requireContext(), HomeActivity.class));
                activity.finish();
            }, 1000);
        }
    }

    public void handleLoginResponse(LoginResponse loginResponse) {
        getApp().login(loginResponse);
    }
}